package org.jeecg.modules.hc.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.google.common.base.Joiner;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.enums.HcAfterSalesStateEnum;
import org.jeecg.modules.hc.service.*;
import org.jeecg.modules.hc.utils.ALiSMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 企业订餐售后
 * @Author: jeecg-boot
 * @Date:   2023-07-15
 * @Version: V1.0
 */
@Api(tags="企业订餐售后")
@RestController
@RequestMapping("/hc/hcCompanyMerchantAfterSales")
@Slf4j
public class HcCompanyMerchantAfterSalesController extends JeecgController<HcCompanyMerchantAfterSales, IHcCompanyMerchantAfterSalesService> {
	@Autowired
	private IHcCompanyMerchantAfterSalesService hcCompanyMerchantAfterSalesService;
	@Autowired
	private ALiSMSUtils aLiSMSUtils;
	@Autowired
	private IHcCompanyInfoService companyInfoService;
	@Autowired
	private IHcMerchantService hcMerchantService;
	@Autowired
	private IHcCompanyFoodOrderService hcCompanyFoodOrderService;
	@Autowired
	private IHcCompanyPickupAddressService companyPickupAddressService;
	@Autowired
	private IHcAfterSalesService hcAfterSalesService;
	@Autowired
	private IHcCompanyMerchantSettingService companyMerchantSettingService;
	@Autowired
	private IHcMerchantService merchantService;
	@Autowired
	private IHcUserService hcUserService;


	@ApiOperation("获取商家售后订单")
	@GetMapping(value = "/getMerchantList")
	public Result<IPage<HcAfterSales>> getMerchantList(HcCompanyMerchantAfterSales param,
													   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
													   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws ParseException {

		if (org.apache.commons.lang3.StringUtils.isNotBlank(param.getTimeBegin())) {
			Date parse = DateUtils.parseDate(param.getTimeBegin(), "yyyy年MM月dd日");
			String beginTime = "";
			String endTime = DateUtils.formatDate(parse, "yyyy-MM-dd") + " 18:00:00";

			Calendar instance = Calendar.getInstance();
			instance.setTime(parse);
			instance.add(Calendar.DAY_OF_MONTH, -1);
			beginTime = DateUtils.formatDate(instance.getTime(), "yyyy-MM-dd") + " 18:00:01";

			param.setTimeBegin(beginTime);
			param.setTimeEnd(endTime);
		}

		Page<HcCompanyMerchantAfterSales> page = new Page<>(pageNo, pageSize);
		IPage<HcCompanyMerchantAfterSales> pageCompanyList = hcCompanyMerchantAfterSalesService.getMerchantList(page, param);

		IPage<HcAfterSales> pageList =new Page<>();
		List<HcAfterSales> afterSales = new ArrayList<>();
		pageCompanyList.getRecords().forEach(a -> {
			List<String> foodName = new ArrayList<>();
			HcAfterSales companySales = new HcAfterSales().setId(a.getId());
			HcOrderMerchant hcOrderMerchant = new HcOrderMerchant();
			String orderCompanyId = a.getOrderCompanyId();
			//价格
			BigDecimal foodPrice = new BigDecimal(0);
			if (orderCompanyId.contains(",")){
				List<String> ids = Arrays.asList(orderCompanyId.split(","));
				List<HcCompanyFoodOrder> hcCompanyFoodOrders = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>().in(HcCompanyFoodOrder::getId, ids));

				hcOrderMerchant.setUserId(hcCompanyFoodOrders.get(0).getUserId());
				hcOrderMerchant.setMerchantId(hcCompanyFoodOrders.get(0).getMerchantId());
				//公司信息
				HcCompanyInfo companyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodOrders.get(0).getCompanyId()));
				hcOrderMerchant.setCompanyName(companyInfo.getCompanyName());

				hcOrderMerchant.setPickingSerialNo(hcCompanyFoodOrders.get(0).getPickingSerialNo());
				hcOrderMerchant.setNameTakingMeal(hcCompanyFoodOrders.get(0).getUsername());

				HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, hcCompanyFoodOrders.get(0).getPickupAddressId()));
				hcOrderMerchant.setPickingAddress(companyInfo.getCompanyName()+companyInfo.getCompanyAddress()+pickupAddress.getPickupAddress());
				hcOrderMerchant.setSupplyAddress(hcCompanyFoodOrders.get(0).getAddressCode());
				for (HcCompanyFoodOrder hcCompanyFoodOrder : hcCompanyFoodOrders) {
					JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
					JSONObject foodObject = foodInfo.getJSONObject("food");
					HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
					//商品数量
					int foodNum = (int) foodInfo.get("foodNum");
					foodName.add(hcCompanyFoodList.getFoodName() +"x"+ foodNum);
					if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
						//获取门店价格
						HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
								.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
								.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
						if (null == companyMerchantSetting){
							companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
						}
						if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
							//获取企业合作价格
							HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
							foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
						}else {
							foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
						}
					}else {
						foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
					}
				}
			}else {
				HcCompanyFoodOrder companyFoodOrder = hcCompanyFoodOrderService.getOne(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getId, orderCompanyId));
				hcOrderMerchant.setUserId(companyFoodOrder.getUserId());
				hcOrderMerchant.setMerchantId(companyFoodOrder.getMerchantId());
				hcOrderMerchant.setPickingSerialNo(companyFoodOrder.getPickingSerialNo());
				hcOrderMerchant.setNameTakingMeal(companyFoodOrder.getUsername());

				//公司信息
				HcCompanyInfo companyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, companyFoodOrder.getCompanyId()));
				hcOrderMerchant.setCompanyName(companyInfo.getCompanyName());

				//取餐地址
				String pickupAddressId = companyFoodOrder.getPickupAddressId();
				HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
				hcOrderMerchant.setPickingAddress(companyInfo.getCompanyName()+companyInfo.getCompanyAddress()+pickupAddress.getPickupAddress());
				hcOrderMerchant.setPickingAddress(companyFoodOrder.getPickupAddress());
				hcOrderMerchant.setSupplyAddress(companyFoodOrder.getAddressCode());
				JSONObject foodInfo = JSONObject.parseObject(companyFoodOrder.getFoodInfo());
				JSONObject foodObject = foodInfo.getJSONObject("food");
				HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
				foodName.add(hcCompanyFoodList.getFoodName() +"x"+ 1);
				//商品数量
				int foodNum = (int) foodInfo.get("foodNum");
				if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
					//获取门店价格
					HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
							.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
							.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
					if (companyMerchantSetting == null) {
						companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0));
					}
					if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
						//获取企业合作价格
						HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
						foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
					}else {
						foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
					}
				}else {
					foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
				}
			}
			companySales.setFeedback(a.getFeedback());
			companySales.setFoodProblems(a.getFoodProblems());
			companySales.setPicture(a.getPicture());
			companySales.setProcessingTime(a.getProcessingTime());
			companySales.setState(a.getState());
			companySales.setStoreName(merchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,a.getMerchantId())).getStoreName());
			companySales.setCompanyId(a.getCompanyId());
			companySales.setMerchantId(a.getMerchantId());
			companySales.setDeductMerchantAmount(a.getDeductMerchantAmount());
			//总价格
			companySales.setTotalPrice(foodPrice);
			//菜品名
			companySales.setNameDishes(foodName.size()>1? Joiner.on("+").join(foodName) :foodName.get(0));
			//投诉次数
			List<HcCompanyMerchantAfterSales> list = hcCompanyMerchantAfterSalesService.list(new LambdaQueryWrapper<HcCompanyMerchantAfterSales>()
					.eq(HcCompanyMerchantAfterSales::getMerchantId, a.getMerchantId()));
			companySales.setComplaintCount((long) list.size());

			companySales.setHcOrderMerchant(hcOrderMerchant);
			companySales.setCreateTime(a.getCreateTime());
			afterSales.add(companySales);
		});
		pageList.setRecords(afterSales);
		pageList.setCurrent(pageCompanyList.getCurrent());
		pageList.setSize(pageCompanyList.getSize());
		pageList.setPages(pageCompanyList.getPages());
		pageList.setTotal(pageCompanyList.getTotal());
		return Result.OK(pageList);
	}


	/**
	 * 分页列表查询
	 *
	 * @param hcCompanyMerchantAfterSales
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "企业订餐售后-分页列表查询")
	@ApiOperation(value="商户企业订餐售后", notes="商户企业订餐售后")
	@GetMapping(value = "/queryMerchantOfCompanyList")
	public Result<IPage<HcAfterSales>> queryMerchantOfCompanyList(HcCompanyMerchantAfterSales hcCompanyMerchantAfterSales,
																	@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																	@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																	HttpServletRequest req) {
		List<HcAfterSales> afterSales = new ArrayList<>();
		//添加企业售后
		List<HcCompanyMerchantAfterSales> all = hcCompanyMerchantAfterSalesService.list(new LambdaQueryWrapper<HcCompanyMerchantAfterSales>()
				.eq(HcCompanyMerchantAfterSales::getMerchantId,hcCompanyMerchantAfterSales.getMerchantId())
				.eq(HcCompanyMerchantAfterSales::getCompanyId,hcCompanyMerchantAfterSales.getCompanyId()));
		all.forEach(a -> {
			List<String> foodName = new ArrayList<>();
			HcAfterSales companySales = new HcAfterSales().setId(a.getId());
			HcOrderMerchant hcOrderMerchant = new HcOrderMerchant();
			String orderCompanyId = a.getOrderCompanyId();
			//价格
			BigDecimal foodPrice = new BigDecimal(0);
			if (orderCompanyId.contains(",")){
				List<String> ids = Arrays.asList(orderCompanyId.split(","));
				List<HcCompanyFoodOrder> hcCompanyFoodOrders = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>().in(HcCompanyFoodOrder::getId, ids));

				hcOrderMerchant.setUserId(hcCompanyFoodOrders.get(0).getUserId());
				hcOrderMerchant.setMerchantId(hcCompanyFoodOrders.get(0).getMerchantId());
				//公司信息
				HcCompanyInfo companyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodOrders.get(0).getCompanyId()));
				hcOrderMerchant.setCompanyName(companyInfo.getCompanyName());

				hcOrderMerchant.setPickingSerialNo(hcCompanyFoodOrders.get(0).getPickingSerialNo());
				hcOrderMerchant.setNameTakingMeal(hcCompanyFoodOrders.get(0).getUsername());

				HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, hcCompanyFoodOrders.get(0).getPickupAddressId()));
				hcOrderMerchant.setPickingAddress(companyInfo.getCompanyName()+companyInfo.getCompanyAddress()+pickupAddress.getPickupAddress());
				hcOrderMerchant.setSupplyAddress(hcCompanyFoodOrders.get(0).getAddressCode());
				for (HcCompanyFoodOrder hcCompanyFoodOrder : hcCompanyFoodOrders) {
					JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
					JSONObject foodObject = foodInfo.getJSONObject("food");
					HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
					//商品数量
					int foodNum = (int) foodInfo.get("foodNum");
					foodName.add(hcCompanyFoodList.getFoodName() +"x"+ foodNum);
					if (hcCompanyFoodList.getCooperatePrice()==null || hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
						//获取门店价格
						HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
								.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
								.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
						if (null == companyMerchantSetting){
							companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
						}
						if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
							//获取企业合作价格
							HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
							foodPrice = foodPrice.add(hcCompanyInfo.getCompanyPrice().multiply(new BigDecimal(foodNum)));
						}else {
							foodPrice = foodPrice.add(companyMerchantSetting.getSalePrice().multiply(new BigDecimal(foodNum)));
						}
					}else {
						foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
					}
				}
			}else {
				HcCompanyFoodOrder companyFoodOrder = hcCompanyFoodOrderService.getOne(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getId, orderCompanyId));
				hcOrderMerchant.setUserId(companyFoodOrder.getUserId());
				hcOrderMerchant.setMerchantId(companyFoodOrder.getMerchantId());
				hcOrderMerchant.setPickingSerialNo(companyFoodOrder.getPickingSerialNo());
				hcOrderMerchant.setNameTakingMeal(companyFoodOrder.getUsername());

				//公司信息
				HcCompanyInfo companyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, companyFoodOrder.getCompanyId()));
				hcOrderMerchant.setCompanyName(companyInfo.getCompanyName());

				//取餐地址
				String pickupAddressId = companyFoodOrder.getPickupAddressId();
				HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
				hcOrderMerchant.setPickingAddress(companyInfo.getCompanyName()+companyInfo.getCompanyAddress()+pickupAddress.getPickupAddress());
				hcOrderMerchant.setPickingAddress(companyFoodOrder.getPickupAddress());
				hcOrderMerchant.setSupplyAddress(companyFoodOrder.getAddressCode());
				JSONObject foodInfo = JSONObject.parseObject(companyFoodOrder.getFoodInfo());
				JSONObject foodObject = foodInfo.getJSONObject("food");
				HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
				foodName.add(hcCompanyFoodList.getFoodName() +"x"+ 1);
				//商品数量
				int foodNum = (int) foodInfo.get("foodNum");
				if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
					//获取门店价格
					HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
							.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
							.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
					if (companyMerchantSetting == null) {
						companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0));
					}
					if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
						//获取企业合作价格
						HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
						foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
					}else {
						foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
					}
				}else {
					foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
				}
			}

			companySales.setUpdateTime(a.getUpdateTime());
			companySales.setFeedback(a.getFeedback());
			companySales.setFoodProblems(a.getFoodProblems());
			companySales.setPicture(a.getPicture());
			companySales.setProcessingTime(a.getProcessingTime());
			companySales.setState(a.getState());
			companySales.setStoreName(merchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,a.getMerchantId())).getStoreName());
			companySales.setCompanyId(a.getCompanyId());
			companySales.setMerchantId(a.getMerchantId());
			companySales.setDeductMerchantAmount(a.getDeductMerchantAmount());
			//总价格
			companySales.setTotalPrice(foodPrice);
			//菜品名
			companySales.setNameDishes(foodName.size()>1? Joiner.on("+").join(foodName) :foodName.get(0));
			//投诉次数
			List<HcCompanyMerchantAfterSales> list = hcCompanyMerchantAfterSalesService.list(new LambdaQueryWrapper<HcCompanyMerchantAfterSales>()
					.eq(HcCompanyMerchantAfterSales::getMerchantId, a.getMerchantId()));
			companySales.setComplaintCount((long) list.size());

			companySales.setHcOrderMerchant(hcOrderMerchant);
			companySales.setCreateTime(a.getCreateTime());
			companySales.setReasonRejection(a.getReasonRejection());
			afterSales.add(companySales);
		});
		afterSales.sort(new Comparator<HcAfterSales>() {
			@Override
			public int compare(HcAfterSales o1, HcAfterSales o2) {
				return o2.getCreateTime().compareTo(o1.getCreateTime());
			}
		});

		int totalRecords = afterSales.size() + all.size(); // 计算总记录数
		// 创建一个 Page 对象，并设置总记录数、每页记录数、当前页数
		IPage<HcAfterSales> pageList = new Page<>(pageNo, pageSize, totalRecords);
		// 计算分页起始索引和结束索引
		int startIndex = (pageNo - 1) * pageSize;
		int endIndex = Math.min(startIndex + pageSize, afterSales.size());
		// 截取需要的分页数据
		List<HcAfterSales> pageData = afterSales.subList(startIndex, endIndex);
		for (HcAfterSales data : pageData) {
			if (org.apache.commons.lang3.StringUtils.isEmpty(data.getCompanyId())){
				hcAfterSalesService.setInformation(data);
			}
		}
		// 设置分页数据
		pageList.setRecords(pageData);
		return Result.OK(pageList);
	}
	/**
	 * 分页列表查询
	 *
	 * @param hcCompanyMerchantAfterSales
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "企业订餐售后-分页列表查询")
	@ApiOperation(value="商户售后订单", notes="商户售后订单")
	@GetMapping(value = "/getMerchantAfterSalesOrders")
	public Result<IPage<HcCompanyMerchantAfterSales>> getMerchantAfterSalesOrders(HcCompanyMerchantAfterSales hcCompanyMerchantAfterSales,
																	@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																	@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																	HttpServletRequest req) {
		QueryWrapper<HcCompanyMerchantAfterSales> queryWrapper = QueryGenerator.initQueryWrapper(hcCompanyMerchantAfterSales, req.getParameterMap());
		Page<HcCompanyMerchantAfterSales> page = new Page<HcCompanyMerchantAfterSales>(pageNo, pageSize);
		IPage<HcCompanyMerchantAfterSales> pageList = hcCompanyMerchantAfterSalesService.page(page, queryWrapper);
		for (HcCompanyMerchantAfterSales record : pageList.getRecords()) {
			String name = "";
			String orderCompanyId = record.getOrderCompanyId();
			if (orderCompanyId.contains(",")){
				List<String> ids = Arrays.asList(orderCompanyId.split(","));
				List<HcCompanyFoodOrder> hcCompanyFoodOrders = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>().in(HcCompanyFoodOrder::getId, ids));
				for (HcCompanyFoodOrder hcCompanyFoodOrder : hcCompanyFoodOrders) {
					Map<String,Object> objectMap = (Map<String, Object>) JSONObject.parse(hcCompanyFoodOrder.getFoodInfo());
					HcCompanyFoodList hcCompanyFoodList = (HcCompanyFoodList) objectMap.get("food");
					name = name + hcCompanyFoodList.getFoodName();
				}
			}
			//菜品名
			record.setNameDishes(name);
			//商户信息
			record.setMerchant(hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>()
					.eq(HcMerchant::getId,hcCompanyMerchantAfterSales.getMerchantId())));
			//企业投诉数量
			record.setComplaintCount(hcCompanyMerchantAfterSalesService.count(new LambdaQueryWrapper<HcCompanyMerchantAfterSales>()
					.eq(HcCompanyMerchantAfterSales::getMerchant,hcCompanyMerchantAfterSales.getMerchantId())));
		}
		return Result.OK(pageList);
	}

	/**
	 * 分页列表查询
	 *
	 * @param hcCompanyMerchantAfterSales
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "企业订餐售后-分页列表查询")
	@ApiOperation(value="企业订餐售后-分页列表查询", notes="企业订餐售后-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<HcCompanyMerchantAfterSales>> queryPageList(HcCompanyMerchantAfterSales hcCompanyMerchantAfterSales,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HcCompanyMerchantAfterSales> queryWrapper = QueryGenerator.initQueryWrapper(hcCompanyMerchantAfterSales, req.getParameterMap());
		Page<HcCompanyMerchantAfterSales> page = new Page<HcCompanyMerchantAfterSales>(pageNo, pageSize);
		IPage<HcCompanyMerchantAfterSales> pageList = hcCompanyMerchantAfterSalesService.page(page, queryWrapper);
		return Result.OK(pageList);
	}


	/**
	 * 分页列表查询
	 *
	 * @param hcCompanyMerchantAfterSales
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "企业订餐售后-分页列表查询")
	@ApiOperation(value="企业订餐售后列表", notes="企业订餐售后列表")
	@GetMapping(value = "/getCompanyAfterSalesList")
	public Result<?> getCompanyAfterSalesList(HcCompanyMerchantAfterSales hcCompanyMerchantAfterSales,
																	@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																	@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																	HttpServletRequest req) {

		if (StringUtils.isNotBlank(hcCompanyMerchantAfterSales.getTimeBegin()) && hcCompanyMerchantAfterSales.getTimeBegin().length() == 16) {
			hcCompanyMerchantAfterSales.setTimeBegin(hcCompanyMerchantAfterSales.getTimeBegin() + ":00");
		}
		if (StringUtils.isNotBlank(hcCompanyMerchantAfterSales.getTimeEnd()) && hcCompanyMerchantAfterSales.getTimeEnd().length() == 16) {
			hcCompanyMerchantAfterSales.setTimeEnd(hcCompanyMerchantAfterSales.getTimeEnd() + ":00");
		}

		LambdaQueryWrapper<HcCompanyMerchantAfterSales> companyMerchantAfterSalesLambdaQueryWrapper = new LambdaQueryWrapper<HcCompanyMerchantAfterSales>();
		if (StringUtils.isNotBlank(hcCompanyMerchantAfterSales.getTimeBegin())) {
			companyMerchantAfterSalesLambdaQueryWrapper.ge(HcCompanyMerchantAfterSales::getCreateTime,hcCompanyMerchantAfterSales.getTimeBegin()+ ":00");
		}
		if (StringUtils.isNotBlank(hcCompanyMerchantAfterSales.getTimeEnd())){
			companyMerchantAfterSalesLambdaQueryWrapper.le(HcCompanyMerchantAfterSales::getCreateTime,hcCompanyMerchantAfterSales.getTimeEnd()+ ":00");
		}
		if (StringUtils.isNotBlank(hcCompanyMerchantAfterSales.getStoreName())){
			List<String> userIds = hcUserService.list(new LambdaQueryWrapper<HcUser>().like(HcUser::getNickname, hcCompanyMerchantAfterSales.getStoreName())).stream().map(HcUser::getId).collect(Collectors.toList());

			List<String> companyOrderNums = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>().like(HcCompanyFoodOrder::getFoodInfo, hcCompanyMerchantAfterSales.getStoreName())).stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());

			companyMerchantAfterSalesLambdaQueryWrapper.in(HcCompanyMerchantAfterSales::getUserId,userIds).or()
					.in(HcCompanyMerchantAfterSales::getOrderOrderNum,companyOrderNums);
		}
		//添加企业售后
		List<HcCompanyMerchantAfterSales> all = hcCompanyMerchantAfterSalesService.list(companyMerchantAfterSalesLambdaQueryWrapper);
		List<HcAfterSales> companyAfterSales = new ArrayList<>();
		all.forEach(a -> {
			List<String> foodName = new ArrayList<>();
			HcAfterSales companySales = new HcAfterSales().setId(a.getId());
			companySales.setPhone(a.getPhone());
			HcOrderMerchant hcOrderMerchant = new HcOrderMerchant();
			String orderCompanyId = a.getOrderCompanyId();
			//价格
			BigDecimal foodPrice = new BigDecimal(0);
			if (orderCompanyId.contains(",")){
				List<String> ids = Arrays.asList(orderCompanyId.split(","));
				List<HcCompanyFoodOrder> hcCompanyFoodOrders = hcCompanyFoodOrderService.list(new LambdaQueryWrapper<HcCompanyFoodOrder>().in(HcCompanyFoodOrder::getId, ids));

				hcOrderMerchant.setUserId(hcCompanyFoodOrders.get(0).getUserId());
				hcOrderMerchant.setMerchantId(hcCompanyFoodOrders.get(0).getMerchantId());
				//公司信息
				HcCompanyInfo companyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodOrders.get(0).getCompanyId()));
				hcOrderMerchant.setCompanyName(companyInfo.getCompanyName());

				hcOrderMerchant.setPickingSerialNo(hcCompanyFoodOrders.get(0).getPickingSerialNo());
				hcOrderMerchant.setNameTakingMeal(hcCompanyFoodOrders.get(0).getUsername());

				HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, hcCompanyFoodOrders.get(0).getPickupAddressId()));
				hcOrderMerchant.setPickingAddress(companyInfo.getCompanyName()+companyInfo.getCompanyAddress()+pickupAddress.getPickupAddress());
				hcOrderMerchant.setSupplyAddress(hcCompanyFoodOrders.get(0).getAddressCode());
				for (HcCompanyFoodOrder hcCompanyFoodOrder : hcCompanyFoodOrders) {
					JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
					JSONObject foodObject = foodInfo.getJSONObject("food");
					HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
					//商品数量
					int foodNum = (int) foodInfo.get("foodNum");
					foodName.add(hcCompanyFoodList.getFoodName() +"x"+ foodNum);
					if (hcCompanyFoodList.getSalePrice()==null || hcCompanyFoodList.getSalePrice().compareTo(new BigDecimal(0)) == 0){
						//获取门店价格
						HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
								.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
								.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
						if (null == companyMerchantSetting){
							companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
						}
						if (companyMerchantSetting.getSalePrice()==null||companyMerchantSetting.getSalePrice().compareTo(new BigDecimal(0))==0){
							//获取企业合作价格
							HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
							foodPrice = foodPrice.add(hcCompanyInfo.getCompanyPrice().multiply(new BigDecimal(foodNum)));
						}else {
							foodPrice = foodPrice.add(companyMerchantSetting.getSalePrice().multiply(new BigDecimal(foodNum)));
						}
					}else {
						foodPrice = foodPrice.add(hcCompanyFoodList.getSalePrice().multiply(new BigDecimal(foodNum)));
					}
				}
			}else {
				HcCompanyFoodOrder companyFoodOrder = hcCompanyFoodOrderService.getOne(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getId, orderCompanyId));
				hcOrderMerchant.setUserId(companyFoodOrder.getUserId());
				hcOrderMerchant.setMerchantId(companyFoodOrder.getMerchantId());
				hcOrderMerchant.setPickingSerialNo(companyFoodOrder.getPickingSerialNo());
				hcOrderMerchant.setNameTakingMeal(companyFoodOrder.getUsername());

				//公司信息
				HcCompanyInfo companyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, companyFoodOrder.getCompanyId()));
				hcOrderMerchant.setCompanyName(companyInfo.getCompanyName());

				//取餐地址
				String pickupAddressId = companyFoodOrder.getPickupAddressId();
				HcCompanyPickupAddress pickupAddress = companyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
				hcOrderMerchant.setPickingAddress(companyInfo.getCompanyName()+companyInfo.getCompanyAddress()+(pickupAddress == null ? "":pickupAddress.getPickupAddress()));
				hcOrderMerchant.setSupplyAddress(companyFoodOrder.getAddressCode());

				JSONObject foodInfo = JSONObject.parseObject(companyFoodOrder.getFoodInfo());
				JSONObject foodObject = foodInfo.getJSONObject("food");
				HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);

				//商品数量
				int foodNum = (int) foodInfo.get("foodNum");
				foodName.add(hcCompanyFoodList.getFoodName() +"x"+ foodNum);
				if (hcCompanyFoodList.getSalePrice()==null||hcCompanyFoodList.getSalePrice().compareTo(new BigDecimal(0)) == 0){
					//获取门店价格
					HcCompanyMerchantSetting companyMerchantSetting = companyMerchantSettingService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
							.eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
							.eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
					if (null == companyMerchantSetting){
						companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
					}
					if (companyMerchantSetting.getSalePrice()==null||companyMerchantSetting.getSalePrice().compareTo(new BigDecimal(0))==0){
						//获取企业合作价格
						HcCompanyInfo hcCompanyInfo = companyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyFoodList.getCompanyId()));
						foodPrice = foodPrice.add(hcCompanyInfo.getCompanyPrice().multiply(new BigDecimal(foodNum)));
					}else {
						foodPrice = foodPrice.add(companyMerchantSetting.getSalePrice().multiply(new BigDecimal(foodNum)));
					}
				}else {
					foodPrice = foodPrice.add(hcCompanyFoodList.getSalePrice().multiply(new BigDecimal(foodNum)));
				}
			}
			companySales.setFeedback(a.getFeedback());
			companySales.setFoodProblems(a.getFoodProblems());
			companySales.setPicture(a.getPicture());
			companySales.setProcessingTime(a.getProcessingTime());
			companySales.setState(a.getState());
			companySales.setStoreName(merchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,a.getMerchantId())).getStoreName());
			companySales.setCompanyId(a.getCompanyId());
			companySales.setMerchantId(a.getMerchantId());
			companySales.setDeductMerchantAmount(a.getDeductMerchantAmount());
			//总价格
			companySales.setTotalPrice(foodPrice);
			//菜品名
			companySales.setNameDishes(foodName.size()>1? Joiner.on("+").join(foodName) :foodName.get(0));
			//投诉次数
			List<HcCompanyMerchantAfterSales> list = hcCompanyMerchantAfterSalesService.list(new LambdaQueryWrapper<HcCompanyMerchantAfterSales>()
					.eq(HcCompanyMerchantAfterSales::getMerchantId, a.getMerchantId()));
			companySales.setComplaintCount((long) list.size());

			companySales.setHcOrderMerchant(hcOrderMerchant);
			companySales.setCreateTime(a.getCreateTime());
			companyAfterSales.add(companySales);
		});
		companyAfterSales.sort(new Comparator<HcAfterSales>() {
			@Override
			public int compare(HcAfterSales o1, HcAfterSales o2) {
				return o2.getCreateTime().compareTo(o1.getCreateTime());
			}
		});
		IPage<HcAfterSales> companyAfterSalesIPage = new PageDTO<>();
		// 设置分页数据
		companyAfterSalesIPage.setCurrent(pageNo);
		companyAfterSalesIPage.setSize(pageSize);
		companyAfterSalesIPage.setTotal(companyAfterSales.size());
		companyAfterSalesIPage.setRecords(companyAfterSales);
		return Result.OK(companyAfterSalesIPage);
	}
	/**
	 *   添加
	 *
	 * @param hcCompanyMerchantAfterSales
	 * @return
	 */
	@AutoLog(value = "企业订餐售后-添加")
	@ApiOperation(value="企业订餐售后-添加", notes="企业订餐售后-添加")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_after_sales:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody HcCompanyMerchantAfterSales hcCompanyMerchantAfterSales) {
		LambdaQueryWrapper<HcCompanyInfo> companyInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
		companyInfoLambdaQueryWrapper.eq(HcCompanyInfo::getId,hcCompanyMerchantAfterSales.getCompanyId());
		HcCompanyInfo companyInfo = companyInfoService.getOne(companyInfoLambdaQueryWrapper);
		String noticePhone = companyInfo.getNoticePhone();
		if (StringUtils.isNotBlank(noticePhone)){
			if (noticePhone.contains(",")){
				List<String> phones = Arrays.asList(noticePhone.split(","));
				for (String phone : phones) {
					aLiSMSUtils.sendMessage(phone.trim(),companyInfo.getCompanyName());
				}
			}else {
				aLiSMSUtils.sendMessage(noticePhone.trim(),companyInfo.getCompanyName());
			}
		}
		hcCompanyMerchantAfterSales.setState(HcAfterSalesStateEnum.NO);
		hcCompanyMerchantAfterSalesService.save(hcCompanyMerchantAfterSales);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hcCompanyMerchantAfterSales
	 * @return
	 */
	@AutoLog(value = "企业订餐售后-编辑")
	@ApiOperation(value="企业订餐售后-编辑", notes="企业订餐售后-编辑")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_after_sales:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody HcCompanyMerchantAfterSales hcCompanyMerchantAfterSales) {
		hcCompanyMerchantAfterSalesService.edit(hcCompanyMerchantAfterSales);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业订餐售后-通过id删除")
	@ApiOperation(value="企业订餐售后-通过id删除", notes="企业订餐售后-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_after_sales:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		hcCompanyMerchantAfterSalesService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "企业订餐售后-批量删除")
	@ApiOperation(value="企业订餐售后-批量删除", notes="企业订餐售后-批量删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_after_sales:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hcCompanyMerchantAfterSalesService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "企业订餐售后-通过id查询")
	@ApiOperation(value="企业订餐售后-通过id查询", notes="企业订餐售后-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<HcCompanyMerchantAfterSales> queryById(@RequestParam(name="id",required=true) String id) {
		HcCompanyMerchantAfterSales hcCompanyMerchantAfterSales = hcCompanyMerchantAfterSalesService.getById(id);
		if(hcCompanyMerchantAfterSales==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hcCompanyMerchantAfterSales);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hcCompanyMerchantAfterSales
    */
    //@RequiresPermissions("org.jeecg.modules:hc_company_merchant_after_sales:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcCompanyMerchantAfterSales hcCompanyMerchantAfterSales) {
        return super.exportXls(request, hcCompanyMerchantAfterSales, HcCompanyMerchantAfterSales.class, "企业订餐售后");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("hc_company_merchant_after_sales:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcCompanyMerchantAfterSales.class);
    }

}
